package com.threeonemeeting.adapter;

import java.util.ArrayList;

import android.app.Activity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.threeonemeeting.Const;
import com.threeonemeeting.R;
import com.threeonemeeting.listcache.MessageInfoCache;
import com.threeonemeeting.model.MessageInfo;
import com.threeonemeeting.util.MiscUtil;

public class MessageInfoListAdapter extends ArrayAdapter<MessageInfo> {

	protected ArrayList<MessageInfo> mMessageList = null;

	public MessageInfoListAdapter(Activity activity) {
		super(activity, 0);
	}

	public void setMessageList(ArrayList<MessageInfo> messageList) {
		mMessageList = messageList;
		notifyDataSetChanged();
	}

	public ArrayList<MessageInfo> getMessageList() {
		return mMessageList;
	}

	@Override
	public void add(MessageInfo messageInfo) {
		if (mMessageList == null)
			mMessageList = new ArrayList<MessageInfo>();

		mMessageList.add(messageInfo);
	}

	public void clear() {
		if (mMessageList != null) {
			mMessageList.clear();
		}
	}

	@Override
	public int getCount() {
		if (mMessageList == null)
			return 0;

		return mMessageList.size();
	}

	@Override
	public MessageInfo getItem(int position) {
		return mMessageList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		Activity activity = (Activity) getContext();

		MessageInfo messageInfo = getItem(position);

		View rowView = convertView;
		MessageInfoCache viewCache;

		if (rowView == null) {
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.lvi_message, null);
			viewCache = new MessageInfoCache(rowView, 0,
					messageInfo.strFromName, messageInfo.strFromTime,
					messageInfo.strFromMsg);
			rowView.setTag(viewCache);
		} else {
			viewCache = (MessageInfoCache) rowView.getTag();
		}

		// 评论者的头像
		String strImageUrl = Const.URL.BASE_HEADERIMG_URL
				+ messageInfo.nFromUserId;
		ImageView headerImageView = viewCache.getSenderHeaderImagetView();
		MiscUtil.setImageView(headerImageView, strImageUrl);

		// 发送消息的人
		TextView senderNameView = viewCache.getSenderNameTextView();
		senderNameView.setText(messageInfo.strFromName);

		// 发送消息的时间
		TextView senderTimeView = viewCache.getSenderTimeTextView();
		senderTimeView.setText(messageInfo.strFromTime);

		// 发送消息的内容
		TextView senderMsgView = viewCache.getSenderMsgTextView();
		senderMsgView.setText(Html.fromHtml(messageInfo.strFromMsg));

		return rowView;
	}
}
